<template>
  <!-- ... 其他代码 ... -->
  <el-form-item label="附件">
    <el-upload
      class="upload-demo"
      action="/api/file/upload"
      :headers="headers"
      :on-success="handleUploadSuccess"
      :on-error="handleUploadError"
      :before-upload="beforeUpload"
    >
      <el-button type="primary">点击上传</el-button>
      <template #tip>
        <div class="el-upload__tip">
          只能上传 jpg/png/pdf 文件，且不超过 10MB
        </div>
      </template>
    </el-upload>
  </el-form-item>
  <!-- ... 其他代码 ... -->
</template>

<script setup>
import { useStore } from 'vuex'
import { computed } from 'vue'

const store = useStore()

// 添加请求头，包含token
const headers = computed(() => ({
  Authorization: store.state.user.token
}))

// 上传前验证
const beforeUpload = (file) => {
  const isValidType = ['image/jpeg', 'image/png', 'application/pdf'].includes(file.type)
  const isLt10M = file.size / 1024 / 1024 < 10

  if (!isValidType) {
    ElMessage.error('只能上传 JPG/PNG/PDF 格式的文件!')
    return false
  }
  if (!isLt10M) {
    ElMessage.error('文件大小不能超过 10MB!')
    return false
  }
  return true
}

// 上传成功回调
const handleUploadSuccess = (response) => {
  form.attachmentUrl = response.data
  ElMessage.success('文件上传成功')
}

// 上传失败回调
const handleUploadError = () => {
  ElMessage.error('文件上传失败')
}
</script> 